<?php

namespace App\Install\Service;

use App\Common\Exception\ApiMessageException;
use App\Common\Model\Base\Route;
use App\Common\Service\AbstractService;
use App\Common\Service\TableInitSqlService;
use think\facade\App;

/**
 * Class InitService
 */
class InitService extends AbstractService
{
    /**
     * @return array
     * @throws \Exception
     * @date 2023/6/28
     */
    public function init(): array
    {
        if (InitService::isInitComplete()){
            throw new ApiMessageException('已初始化完成，无需重复操作');
        }

        $init = TableInitSqlService::aop(false)->extractInitData(App::getRootPath() . '/app/Common/Model');

        $errorMsg = [];
        $init->runCreateSql($errorMsg);
        $init->runInitData($errorMsg);

        $errorMsg or $this->successFileCreate();

        return $errorMsg;
    }

    /**
     * @return string
     */
    private static function getInstallLockFilename(): string
    {
        return __DIR__ . '/../install.lock';
    }

    /**
     * @return bool
     */
    private function successFileCreate(): bool
    {
        $file = self::getInstallLockFilename();

        return (bool)file_put_contents($file, '如需重新安装，请删掉此文件');
    }

    /**
     * 是否已初始化
     *
     * @return bool
     */
    public static function isInitComplete(): bool
    {
        return file_exists(self::getInstallLockFilename());
    }
}